import type { AxiosResponse } from 'axios';
import { BACKEND_ERROR_CODE, createFlatRequest } from '@sa/axios';
import { useAuthStore } from '@/store/modules/auth';
import { $t } from '@/locales';
import { getServiceBaseURL } from '@/utils/service';
import { getAuthorization, handleExpiredRequest, showErrorMsg } from './shared';
import type { RequestInstanceState } from './type';

// 客户端请求配置
const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';

// 客户端API请求基础URL配置
const CLIENT_BASE_URL = isHttpProxy ? '/proxy-client' : 'http://localhost:9500';

// 创建客户端请求实例
export const clientRequest = createFlatRequest<App.Service.Response, RequestInstanceState>(
  {
    baseURL: CLIENT_BASE_URL,
    headers: {
      apifoxToken: 'XL299LiMEDZ0H5h3A29PxwQXdMJqWyY2'
    }
  },
  {
    async onRequest(config) {
      // 处理token
      if (!(config as any).noNeedToken) {
        const Authorization = getAuthorization();
        Object.assign(config.headers, { Authorization });
      }

      return config;
    },
    isBackendSuccess(response) {
      // 与主请求实例保持一致的成功码判断逻辑
      return String(response.data.code) === import.meta.env.VITE_SERVICE_SUCCESS_CODE;
    },
    async onBackendFail(response, instance) {
      const authStore = useAuthStore();
      const responseCode = String(response.data.code);

      function handleLogout() {
        authStore.resetStore();
      }

      function logoutAndCleanup() {
        handleLogout();
        window.removeEventListener('beforeunload', handleLogout);

        clientRequest.state.errMsgStack = clientRequest.state.errMsgStack.filter(msg => msg !== response.data.msg);
      }

      // 处理登出逻辑
      const logoutCodes = import.meta.env.VITE_SERVICE_LOGOUT_CODES?.split(',') || [];
      if (logoutCodes.includes(responseCode)) {
        handleLogout();
        return null;
      }

      // 处理模态框登出逻辑
      const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      if (modalLogoutCodes.includes(responseCode) && !clientRequest.state.errMsgStack?.includes(response.data.msg)) {
        clientRequest.state.errMsgStack = [...(clientRequest.state.errMsgStack || []), response.data.msg];

        // 防止用户刷新页面
        window.addEventListener('beforeunload', handleLogout);

        window.$messageBox
          ?.confirm(response.data.msg, $t('common.error'), {
            confirmButtonText: $t('common.confirm'),
            cancelButtonText: $t('common.cancel'),
            type: 'error',
            closeOnClickModal: false,
            closeOnPressEscape: false
          })
          .then(() => {
            logoutAndCleanup();
          });

        return null;
      }

      // 处理token过期逻辑
      const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
      if (expiredTokenCodes.includes(responseCode)) {
        const success = await handleExpiredRequest(clientRequest.state);
        if (success) {
          const Authorization = getAuthorization();
          Object.assign(response.config.headers, { Authorization });

          return instance.request(response.config) as Promise<AxiosResponse>;
        }
      }

      return null;
    },
    transformBackendResponse(response) {
      return response.data.data;
    },
    onError(error) {
      let message = error.message;
      let backendErrorCode = '';

      // 获取后端错误信息和代码
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.msg || message;
        backendErrorCode = String(error.response?.data?.code || '');
      }

      // 模态框中显示的错误信息
      const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      if (modalLogoutCodes.includes(backendErrorCode)) {
        return;
      }

      // token过期时，刷新token并重试请求，因此无需显示错误信息
      const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];
      if (expiredTokenCodes.includes(backendErrorCode)) {
        return;
      }

      showErrorMsg(clientRequest.state, message);
    }
  }
); 